package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Reference
    private RoleService roleService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return roleService.pageQuery(queryPageBean);
    }


    /**
     * 查询所有的角色信息
     * @return
     */
    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            //调用业务层方法查询所有的角色信息
            List<Role> list = roleService.findAll();
            return new Result(true,"角色信息查询成功",list);//查询成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "角色信息查询失败");//查询失败
        }
    }

    /**
     * 添加权限信息
     * @param role 角色信息
     * @param permissionIds 权限id
     * @return
     */
    @RequestMapping("/edit")
    public Result add(@RequestBody Role role,Integer[] permissionIds){
        try{
            //调用业务层方法为角色添加权限信息
            roleService.edit(role,permissionIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"新增权限信息失败");//新增失败
        }
        return new Result(true,"新增权限信息成功");//新增成功
    }

    /**
     * 根据id查询角色信息
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            ////调用业务层方法根据id查找角色信息
            Role role = roleService.findById(id);
            return new Result(true,"角色信息查询成功",role);//查询成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"角色信息查询失败");//查询失败
        }
    }

    /**
     * 根据角色id找到权限id，用于复选框勾选
     * @param id
     * @return
     */
    @RequestMapping("/findRoleIdsByPermissionId")
    public Result findRoleIdsByPermissionId(Integer id){
        try{
            List<Integer> permissionIds = roleService.findRoleIdsByPermissionId(id);
            return new Result(true,"权限id查询成功",permissionIds);//查询成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "权限id查询失败");//查询失败
        }
    }
}
